let DateUtil = require("../../utils/dateUtil");
let pomelo = require("pomelo");

function Mail() {
    this.mailData = null;
    this.isNew = false;
    this.readTime = 0;
}

Mail.prototype.getId = function(){
    if (this.mailData != null) {
        return this.mailData.getId();
    } else {
        return 0;
    }
};

Mail.prototype.getAward = function () {
    return this.mailData.getAward();
};

Mail.prototype.getIsNew = function(){
    return this.isNew;
};

Mail.prototype.readOrClaim = function (player) {
    this.isNew = false;
    this.readTime = DateUtil.nowMS();
    if (this.hasAward()) {
        let award = this.mailData.getAward();
        if (award.currencyType === "diamond") {
            player.changeDiamond(award.amount);
        }
        if (award.currencyType === "gold") {
            player.changeGold(award.amount);
        }
        if (award.currencyType === "fangka") {
            player.changeFangka(award.amount);
        }
        let amqpService = pomelo.app.get("amqpService");
        let exchange = 'kd_game_log_ex';
        let routeKey = 'game_log';

        let msg = {
            type : 'user_receive',
            uid : player.getUid(),
            currencyType : award.currencyType,
            amount: award.amount,
            action : 'mail',
            time : DateUtil.nowMS(),
            channel : player.getUserChannel()
        };
        amqpService.sendMsg(exchange, routeKey, msg);
        return true;
    }
    return false;
};

Mail.prototype.toJSON = function () {
    let data = {
        id : this.mailData.getId(),
        isNew: this.isNew ? 1 : 0,
        title : this.mailData.getTitle(),
        content: this.mailData.getContent(),
        time: Math.round(this.mailData.getSenderTime() / 1000)
    };
    if (this.mailData.hasAward()) {
        data["award"] = this.mailData.getAward();
    }
    return data;
};

Mail.prototype.getSenderTime = function () {
    return this.mailData.getSenderTime();
};

Mail.prototype.getReadTime = function(){
    return this.readTime;
};

Mail.prototype.hasAward = function () {
    return this.mailData.hasAward();
};

module.exports.create = function (mailData, isNew, readTime) {
     let mail = new Mail();
     mail.mailData = mailData;
     mail.isNew = isNew;
     mail.readTime = readTime;
     return mail;
};